package com.example.springboot.ytest.ytool;

import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	public static boolean isEmpty(String str) {
		if (str == null) {
			return true;
		} else if("null".equalsIgnoreCase(str)) {
			return true;
		} else {
			str = str.trim();
			if (str.equals("")) {
				return true;
			}
		}
		return false;
	}
	
	public static boolean isNotEmpty(String str){
	    return !isEmpty(str);
	}
	
	public static String upperFirstChar(String str) {
		if(str!=null && str!=""){
			str  = str.substring(0,1).toUpperCase()+str.substring(1);
		}
		return str;
	}
	
	public static String upperFirstChar2(String src) { // 没有空判断
		return src.substring(0, 1).toUpperCase().concat(src.substring(1));
	}
	
	// product_id -> productId
	public static String dbFieldToBeanField(String dbField){
		int index = dbField.indexOf("_");
		if( -1==index )
			return dbField;
		
		StringBuilder result = new StringBuilder();
		result.append(dbField.substring(0,index));
		String after = dbField.substring(index+1);
		after = upperFirstChar(after);
		after = dbFieldToBeanField(after); // 如果有多个下划线则递归
		result.append(after);
		
		return result.toString();
	}
	
	private static final String UNDERLINE = "_";
	// 类字段(驼峰风格)转成下划线数据库字段（下划线风格）
	public static String camelcase2Underscore(String fieldName){
		StringBuffer builder = new StringBuffer();
		char[] charArray = fieldName.toCharArray();
		for(int index = 0; index < charArray.length; index++) {
			char ch = charArray[index];
			if(Character.isUpperCase(ch)) {
				if(index == 0) {
					builder.append(Character.toLowerCase(ch));
				} else {
					builder.append(UNDERLINE);
					builder.append(Character.toLowerCase(ch));
				}
			} else {
				builder.append(ch);
			}
		}
		return builder.toString();
	}
	
	/**
     * 用逗号分隔的字符串转成数组
     */
    public static List<String> asList(String ids) {
        List<String> idList = new LinkedList<String>();
        if (StringUtil.isNotEmpty(ids)) {
            String idGroup[] = ids.split(",");
            for (String id : idGroup) {
                if(StringUtil.isNotEmpty(id)) {
                    idList.add(id.trim());
                }
            }
        }
        return idList;
    }
    
    /**
     * 用逗号分隔的字符串转成数字数组
     */
    public static List<Integer> asIntegerList(String ids) {
        List<Integer> idList = new LinkedList<Integer>();
        if (StringUtil.isNotEmpty(ids)) {
            String idGroup[] = ids.split(",");
            for (String id : idGroup) {
                if(StringUtil.isNotEmpty(id)) {
                    idList.add(Integer.parseInt(id.trim()));
                }
            }
        }
        return idList;
    }
    
    /**
     * 将  s 中多个匹配正则的字符串返回
     * @param s 输入字符串
     * @param regex 正则表达式
     * @return 匹配正则的字符串 list
     * @author yeyi
     *2017年9月12日
     */
    public static List<String> regexMatchList(String s, String regex) {
        List<String> sList = new LinkedList<>();
        if( isEmpty(s) )
            return sList;
        
        Pattern r = Pattern.compile(regex);
        Matcher m = r.matcher(s);
        while( m.find() ){
            sList.add(m.group());
        }
        return sList;
    }
    
    /**
     * 将  s 中多个匹配正则的字符串返回
     * @param s 输入字符串
     * @param regex 正则表达式
     * @param gap 分隔多个匹配的字符串
     * @return 匹配正则的字符串并用 gap 分隔
     * @author yeyi
     *2017年9月12日
     */
    public static String regexMatchGap(String s, String regex, String gap) {
        StringBuilder result = new StringBuilder();
        if( isEmpty(s) )
            return result.toString();
        
        Pattern r = Pattern.compile(regex);
        Matcher m = r.matcher(s);
        while( m.find() ){
            result.append(m.group());
            result.append(gap);
        }
        
        return result.substring(0, result.length()-gap.length());
    }
    
    /**
     * 将ids看成一个数据集，返回分页后的此数据集:
     * 例如: 
     * ids: 1,2,3,4,5,6,7
     * page: 2
     * pageSize: 3
     * delimiter: ,
     * @return 即取ids第二页的数据：4,5,6
     */
    public static String getPageIds(String stringIds, int page, int pageSize, String delimiter){
        if(page<1 || pageSize<=1){
            throw new RuntimeException("getPageIds param error");
        }
        
        List<Integer> ids = StringUtil.asIntegerList(stringIds);
        if(CollectionUtils.isEmpty(ids)){
            return "";
        }
        
        int fromIndex = (page-1)*pageSize;
        if(fromIndex>ids.size()){
            return "";
        }
        int toIndex = page*pageSize;
        List<Integer> resultList = ids.subList(fromIndex, toIndex<ids.size() ? toIndex : ids.size());
        if(CollectionUtils.isEmpty(resultList)){
            return "";
        }
        
        StringBuilder result = new StringBuilder();
        for(Integer i: resultList){
            result.append(i);
            result.append(",");
        }
        result.deleteCharAt(result.length()-1);
        return result.toString();
    }
    
    public static String getRandomNumber(int num){
        if( num<=0 ) num = 4;
        String randomStr = new String("");
        int n[] = new int[num];
        for (int i=0;i<n.length;i++){
            n[i] = Math.abs(new Random().nextInt(10));
            
            randomStr = randomStr + String.valueOf(n[i]);
        }
        
        return randomStr;
    }
    
    /*方法二：推荐，速度最快
     * https://www.cnblogs.com/heyuxiu/p/5972187.html
     * 判断是否为整数 
     * @param str 传入的字符串 
     * @return 是整数返回true,否则返回false 
   */
    public static boolean isNumeric(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
	}
    
    /**
     * 从 url 中取文件名（最后一个/后的字符串）
     * @author yeyi
     *2018年8月22日
     */
    public static String getFileName(String url) {
		if(isEmpty(url)) {
			return "";
		}
		
		return url.substring(url.lastIndexOf('/')+1, url.length());
	}
    
    public static void main(String[] args) {
//        String string = "camelcase2Underscore";
//        System.out.println(camelcase2Underscore(string));
        
//        String ss = "123,wq,哈哈";
//        List<String> sList = asList(ss);
//        System.out.println(sList);
//        ss = "12333,0,3";
//        List<Integer> iList = asIntegerList(ss);
//        System.out.println(iList);
//        
//        String s2 = ";ABC;;SSS;;;_;;;;,";
//        System.out.println(regexMatchList(s2,";+"));
//        System.out.println(regexMatchGap(s2,";+",","));
        
        String stringIds = "1,2,3,4,5,6,7,8,9,0";
        int page = 2;
        int pageSize = 6;
        String delimiter = ",";
        String out = getPageIds(stringIds, page, pageSize, delimiter);
        System.out.println(out);
        
		String s1 = null;
		String s2 = "";
		String s3 = "abc.jpg";
		String s4 = "www.xxx.com/aaa.jpg";
		System.out.println(getFileName(s1));
		System.out.println(getFileName(s2));
		System.out.println(getFileName(s3));
		System.out.println(getFileName(s4));
    }
}
